#!/usr/bin/env node

const http = require('http'),
      qs  = require('querystring');

let items = [];

function genpage(){
  let dom = items.map(i => '<li>' + i + '</li>').join('\n');
  let html = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>ToDo List</title>
    </head>
    <body>
      <h1>ToDo List</h1>
      <form method="POST" action="http://192.168.150.144:8000">
        <lable>用户名:</lable>
        <input type="text" name="item"/>
        <input type="submit" name="submit"/>
      </form>
      <ul id="items">
      ${dom}
      </ul>
    </body>
    </html>`;
  return html;
}


http.createServer((req,res)=>{
  //status code 
  //header txt/html
  if(req.url !=='/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }

  let data = '';
  req.on('data',chunck => data += chunck);
  req.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !== ''&& typeof item !=='undefined'){
      items.push(item);
    }
    res.writeHead(200,{
      'content-type':'text/html',
      'content-length':Buffer.byteLength(genpage())
    });  

    res.end(genpage());
  });

}).listen(8000);

